package com.chenl.consumer.Logger;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Aspect
@Component
public class LogExporterAspect {
    @Around("@annotation(com.chenl.consumer.Logger.LogAspect)")
    public Object methodExporter(ProceedingJoinPoint joinPoint) throws Throwable{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        LogThreadLocal.setURI(request.getRequestURI());
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        long startTime = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        BigDecimal exeTime = new BigDecimal(endTime).subtract(new BigDecimal(startTime)).divide(new BigDecimal(1000));//获取方法执行的时间 单位:秒
        LogVo logVo = LogThreadLocal.get();
        Map<String, String> exeTimeMap=new HashMap<>();
        exeTimeMap.put(request.getRequestURI(),exeTime+"秒");
        logVo.setExeTime(exeTimeMap);
        log.info(JSONObject.toJSONString(LogThreadLocal.get()));
        response.addHeader("log", URLEncoder.encode(JSONObject.toJSONString(LogThreadLocal.get())));//设置响应头
        System.out.println("拉拉啊了:"+response.getHeader("log"));
        return proceed;
    }
}
